package com.hxexp.weixin.mvc.passenger.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hxexp.weixin.common.cache.TokenCacheManager;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.constant.CookieName;
import com.hxexp.weixin.constant.Errcode;
import com.hxexp.weixin.constant.Gender;
import com.hxexp.weixin.constant.IdentificationType;
import com.hxexp.weixin.constant.PassengerIdentificationType;
import com.hxexp.weixin.constant.PassengerType;
import com.hxexp.weixin.constant.Privilege;
import com.hxexp.weixin.constant.ReferType;
import com.hxexp.weixin.constant.StartStationsId;
import com.hxexp.weixin.constant.StringConstant;
import com.hxexp.weixin.constant.WebAppVersion;
import com.hxexp.weixin.hpe.api.addpassenger.model.AddPassengerParamBean;
import com.hxexp.weixin.hpe.api.addpassenger.model.AddPassengerResultBean;
import com.hxexp.weixin.hpe.api.delpassenger.model.DelPassengerParamBean;
import com.hxexp.weixin.hpe.api.delpassenger.model.DelPassengerResultBean;
import com.hxexp.weixin.hpe.api.login.model.LoginResultBean;
import com.hxexp.weixin.hpe.api.ordersubmit.model.OrderSubmitBean;
import com.hxexp.weixin.hpe.api.ordersubmit.model.OrderSubmitResultBean;
import com.hxexp.weixin.hpe.api.passengerlist.model.PassengerBean;
import com.hxexp.weixin.hpe.api.passengerlist.model.PassengerListResultBean;
import com.hxexp.weixin.hpe.api.querypassenger.model.QueryPassengerResultBean;
import com.hxexp.weixin.hpe.api.updatepassenger.model.UpdatePassengerParamBean;
import com.hxexp.weixin.hpe.api.updatepassenger.model.UpdatePassengerResultBean;
import com.hxexp.weixin.mvc.common.service.CertificateTypeService;
import com.hxexp.weixin.mvc.common.service.PassengerTypeService;
import com.hxexp.weixin.mvc.passenger.model.OrderPaymentInfoBean;
import com.hxexp.weixin.mvc.passenger.service.PassengerService;

/**
 * 常用乘车人控制器
 *
 * @author wang.bin
 * @author li.jiang
 */
@Controller
@RequestMapping(value = "/passenger")
public final class PassengerController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PassengerController.class);
    private static final String PASSENGERLIST_ATTR = "passengerlist"; // NOSONAR
    private static final String ORDERPAYMENTINFO_ATTR = "orderPaymentInfo";
    private static final String GENDERMAP_ATTR = "gendermap";
    private static final String IDENTIFICATIONTYPEMAP_ATTR = "identificationTypeMap";
    private static final String PASSENGERTYPEMAP_ATTR = "passengerTypeMap";
    private static final String PASSENGERINFO_ATTR = "passengerinfo";
    private static final String HASPRIVILEGE_ATTR = "hasPrivilege";
    @Autowired
    private PassengerService passengerService;
    @Autowired
    private TokenCacheManager tokenCacheManager;
    @Autowired
    private PassengerTypeService passengerTypeService;
    @Autowired
    private CertificateTypeService certificateTypeService;

    /**
     * 设置页面需要的常量
     *
     * @return
     */
    @ModelAttribute("constant")
    public Map<String, String> setConstant() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("passengerType_adult", PassengerType.ADULT); // 乘客类型：成人
        map.put("passengerType_child", PassengerType.CHILD); // 乘客类型：儿童
        map.put("passengerType_special", PassengerType.SPECIAL); // 乘客类型：军残
        map.put("identificationType_idcard", PassengerIdentificationType.IDCARD); // 乘客证件类型：身份证
        map.put("identificationType_officercard", PassengerIdentificationType.OFFICERCARD); // 乘客证件类型：军官证

        map.put("refer_ordersubmit", ReferType.REFER_ORDERCONFIRM);// 来源于确认订单页面

        map.put("idcard", IdentificationType.IDCARD);// 身份证
        map.put("lzxy_startstation_id", StartStationsId.LZXY);// 叙永汽车站ID
        map.put("privilege_amount", Privilege.ULLINE_PRIVILEGE_AMOUNT);// 优惠金额
        map.put("appver_ylns", WebAppVersion.YLNS); // 四川仪陇农商银行
        map.put("appver_nc", WebAppVersion.NC);// 南充当代运业

        return map;
    }

    /**
     * 常用乘车人列表页面
     *
     * @param model
     * @return 常用乘车人列表视图名
     */
    @RequestMapping(value = "/list")
    public String passengerList(@CookieValue(value = CookieName.TOKEN, defaultValue = StringConstant.BLANK) String loginToken, String token,
                                OrderPaymentInfoBean orderPaymentInfo, Model model) {
        PassengerListResultBean passengerListResultBean = new PassengerListResultBean();
        try {
            if (!StringUtils.isEmpty(token)) {
                loginToken = token;
            }
            // 从缓存中获取登陆用户信息
            LoginResultBean loginResultBean = tokenCacheManager.getUserFromCache(loginToken);
            String userId = loginResultBean.getUserId();

            passengerListResultBean = passengerService.getPassengerList(userId);

        } catch (ServiceException e) {
            LOGGER.error("调用常用乘车人列表时发生异常", e); // NOSONAR
        }
        model.addAttribute(PASSENGERLIST_ATTR, passengerListResultBean);
        model.addAttribute(ORDERPAYMENTINFO_ATTR, orderPaymentInfo);

        return "passengerlist"; // NOSONAR
    }

    /**
     * 新增常用乘车人页面
     *
     * @param model
     * @return 新增常用乘车人视图名
     */
    @RequestMapping(value = "/new")
    public String newPassenger(OrderPaymentInfoBean orderPaymentInfoBean, Model model) {
        Map<String, String> genderMap = Gender.CODE_NAME_MAP;
        Map<String, String> identificationTypeMap = new HashMap<String, String>();
        Map<String, String> passengerTypeMap = new HashMap<String, String>();
        setMapKV(identificationTypeMap, passengerTypeMap, orderPaymentInfoBean.getStartstationId());

        model.addAttribute(GENDERMAP_ATTR, genderMap);
        model.addAttribute(IDENTIFICATIONTYPEMAP_ATTR, identificationTypeMap);
        model.addAttribute(PASSENGERTYPEMAP_ATTR, passengerTypeMap);
        model.addAttribute(PASSENGERINFO_ATTR, orderPaymentInfoBean);

        return "passenger_new";
    }

    /**
     * 新增常用乘车人
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public AddPassengerResultBean addNewPassenger(@CookieValue(value = CookieName.TOKEN, defaultValue = StringConstant.BLANK) String token,
                                                  AddPassengerParamBean addPassengerParamBean) {
        AddPassengerResultBean addPassengerResultBean = null;
        // 从缓存中获取登陆用户信息
        LoginResultBean loginResultBean = tokenCacheManager.getUserFromCache(token);
        String userId = loginResultBean.getUserId();
        try {
            // 设置用户ID
            addPassengerParamBean.setUserId(userId);
            addPassengerResultBean = passengerService.addNewPassenger(addPassengerParamBean);
        } catch (ServiceException e) {
            LOGGER.error("调用新增常用乘车人时发生异常", e); // NOSONAR
            addPassengerResultBean = new AddPassengerResultBean();
            addPassengerResultBean.setErrcode(Errcode.SERVER_INTERNAL_ERROR);
            addPassengerResultBean.setErrmsg(Errcode.getMessage(Errcode.SERVER_INTERNAL_ERROR));
        }

        return addPassengerResultBean;
    }

    /**
     * 编辑常用乘车人页面
     *
     * @param model
     * @return 编辑常用乘车人视图名
     */
    @RequestMapping(value = "/edit")
    public String editPassenger(PassengerBean passengerBean, OrderPaymentInfoBean orderPaymentInfoBean, Model model) {
        Map<String, String> genderMap = Gender.CODE_NAME_MAP;
        Map<String, String> identificationTypeMap = new HashMap<String, String>();
        Map<String, String> passengerTypeMap = new HashMap<String, String>();
        QueryPassengerResultBean queryPassengerResultBean = new QueryPassengerResultBean();
        setMapKV(identificationTypeMap, passengerTypeMap, orderPaymentInfoBean.getStartstationId());

        try {
            queryPassengerResultBean = passengerService.queryPassengerInfo(passengerBean.getPassengerId());
        } catch (ServiceException e) {
            LOGGER.error("调用查询常用乘车人时发生异常", e); // NOSONAR
        }
        model.addAttribute(GENDERMAP_ATTR, genderMap);
        model.addAttribute(IDENTIFICATIONTYPEMAP_ATTR, identificationTypeMap);
        model.addAttribute(PASSENGERTYPEMAP_ATTR, passengerTypeMap);
        model.addAttribute("passengerbean", queryPassengerResultBean);
        model.addAttribute(PASSENGERINFO_ATTR, orderPaymentInfoBean);

        return "passenger_edit";
    }

    /**
     * 设置车站支持的乘客类型和证件类型
     *
     * @param identificationTypeMap
     * @param passengerTypeMap
     * @param startStationId
     */
    private void setMapKV(Map<String, String> identificationTypeMap, Map<String, String> passengerTypeMap, String startStationId) {
        // 添加车站默认支持的成人乘客类型
        passengerTypeMap.put(PassengerType.ADULT, PassengerType.CODE_NAME_MAP.get(PassengerType.ADULT));
        // 判断车站是否支持儿童乘客类型
        if (passengerTypeService.isSupportChild(startStationId)) {
            passengerTypeMap.put(PassengerType.CHILD, PassengerType.CODE_NAME_MAP.get(PassengerType.CHILD));
        }
        // 判断车站是否支持军残乘客类型
        if (passengerTypeService.isSupportSpecial(startStationId)) {
            passengerTypeMap.put(PassengerType.SPECIAL, PassengerType.CODE_NAME_MAP.get(PassengerType.SPECIAL));
        }

        // 添加车站默认支持的身份证证件类型
        identificationTypeMap.put(PassengerIdentificationType.IDCARD,
                PassengerIdentificationType.CODE_NAME_MAP.get(PassengerIdentificationType.IDCARD));
        // 判断车站是否支持护照证件类型
        if (certificateTypeService.isSupportPassport(startStationId)) {
            identificationTypeMap.put(PassengerIdentificationType.PASSPORT,
                    PassengerIdentificationType.CODE_NAME_MAP.get(PassengerIdentificationType.PASSPORT));
        }
        // 判断车站是否支持军官证证件类型
        if (certificateTypeService.isSupportOfficers(startStationId)) {
            identificationTypeMap.put(PassengerIdentificationType.OFFICERCARD,
                    PassengerIdentificationType.CODE_NAME_MAP.get(PassengerIdentificationType.OFFICERCARD));
        }
    }

    /**
     * 修改常用乘车人
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public UpdatePassengerResultBean updatePassenger(UpdatePassengerParamBean updatePassengerParamBean) {
        UpdatePassengerResultBean updatePassengerResultBean = null;
        try {
            String str = updatePassengerParamBean.getMobile().trim();
            updatePassengerParamBean.setMobile(str);
            updatePassengerResultBean = passengerService.updatePassenger(updatePassengerParamBean);
        } catch (ServiceException e) {
            LOGGER.error("调用新增常用乘车人时发生异常", e); // NOSONAR
            updatePassengerResultBean = new UpdatePassengerResultBean();
            updatePassengerResultBean.setErrcode(Errcode.SERVER_INTERNAL_ERROR);
            updatePassengerResultBean.setErrmsg(Errcode.getMessage(Errcode.SERVER_INTERNAL_ERROR));
        }

        return updatePassengerResultBean;
    }

    /**
     * 删除常用乘车人
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public DelPassengerResultBean delPassenger(String passengerId) {
        DelPassengerResultBean delPassengerResultBean = new DelPassengerResultBean();
        try {
            DelPassengerParamBean delPassengerParamBean = new DelPassengerParamBean();
            delPassengerParamBean.setPassengerId(passengerId);
            delPassengerResultBean = passengerService.delPassenger(delPassengerParamBean);
        } catch (ServiceException e) {
            LOGGER.error("调用删除常用乘车人时发生异常", e); // NOSONAR
            delPassengerResultBean.setErrcode(Errcode.SERVER_INTERNAL_ERROR);
            delPassengerResultBean.setErrmsg(Errcode.getMessage(Errcode.SERVER_INTERNAL_ERROR));
        }

        return delPassengerResultBean;
    }

    /**
     * 支付前修改乘车人信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/select")
    public String selectPassenger(@CookieValue(value = CookieName.TOKEN, defaultValue = StringConstant.BLANK) String token, OrderPaymentInfoBean orderPaymentInfo, String passengerIds, Model model) {
        String[] passengerId = passengerIds.split(",");
        PassengerListResultBean passengerListResult = new PassengerListResultBean();
        try {
            // 从缓存中获取登陆用户信息
            LoginResultBean loginResultBean = tokenCacheManager.getUserFromCache(token);
            String userId = loginResultBean.getUserId();

            passengerListResult = passengerService.getPassengerList(userId);

        } catch (ServiceException e) {
            LOGGER.error("调用常用乘车人列表时发生异常", e); // NOSONAR
        }

        model.addAttribute("passengerId", passengerId);
        model.addAttribute(PASSENGERLIST_ATTR, passengerListResult);
        model.addAttribute(ORDERPAYMENTINFO_ATTR, orderPaymentInfo);

        return "passengerlist"; // NOSONAR
    }

    /**
     * 常用乘车人列表返回添加乘客页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/toaddpassenger")
    public String backAddPassenger(OrderPaymentInfoBean orderPaymentInfo, String refer, Model model) {

        OrderSubmitResultBean orderSubmitResult = new OrderSubmitResultBean();

        OrderSubmitBean orderSubmit = new OrderSubmitBean();
        orderSubmit.setPrice(orderPaymentInfo.getPrice());
        orderSubmit.setHalfPrice(orderPaymentInfo.getHalfPrice());
        List<OrderSubmitBean> orderSubmitList = new ArrayList<OrderSubmitBean>();
        orderSubmitList.add(orderSubmit);

        orderSubmitResult.setOrderTickets(orderSubmitList);
        orderSubmitResult.setSchType(orderPaymentInfo.getSchType());
        orderSubmitResult.setRegBusNo(orderPaymentInfo.getRegBusNo());
        orderSubmitResult.setBusTypeName(orderPaymentInfo.getBusTypeName());
        orderSubmitResult.setStartStationName(orderPaymentInfo.getStartStationName());
        orderSubmitResult.setArriveStationName(orderPaymentInfo.getArriveStationName());
        orderSubmitResult.setLeaveDate(orderPaymentInfo.getLeaveDate());
        orderSubmitResult.setLeaveTime(orderPaymentInfo.getLeaveTime());
        orderSubmitResult.setOrderId(orderPaymentInfo.getOrderId());
        orderSubmitResult.setFullTicketNum(orderPaymentInfo.getFullTicketNum());
        orderSubmitResult.setHalfTicketNum(orderPaymentInfo.getHalfTicketNum());
        orderSubmitResult.setFreeTicketNum(orderPaymentInfo.getFreeTicketNum());

        if (orderPaymentInfo.isHasPrivilege()) {
            model.addAttribute(HASPRIVILEGE_ATTR, true);
        } else {
            model.addAttribute(HASPRIVILEGE_ATTR, false);
        }
        model.addAttribute("serviceprice", orderPaymentInfo.getServiceprice());
        model.addAttribute("totalprices", orderPaymentInfo.getTotalprices());
        model.addAttribute("result", orderSubmitResult);
        model.addAttribute("refer", refer);
        model.addAttribute("startstationid", orderPaymentInfo.getStartstationId());
        model.addAttribute("totalPrivilegeAmount", orderPaymentInfo.getTotalPrivilegeAmount());

        return "add_passenger";
    }

}
